<?php
class interfacer{
    public static function Run(){
        call_user_func("interfacer::".$_SERVER["REQUEST_METHOD"]."_".$_GET["p"]);
    }

    public static function GET_list(){
        if(!file_exists($_GET["s_project_path"]."/data/interface.json")){
            echo json_encode([
                "res"=>"OK","list"=>[]
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_GET["s_project_path"]."/data/interface.json"),true);
        echo json_encode([
            "res"=>"OK","list"=>$data
        ]);
    }

    public static function POST_add(){
        if(!file_exists($_POST["s_project_path"]."/data/interface.json")){
            file_put_contents($_POST["s_project_path"]."/data/interface.json","[]");
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/interface.json"),true);

        $request=[];
        $response=[];
        if(isset($_POST["request_en"])){
            for($i=0;$i<count($_POST["request_en"]);$i++){
                array_push($request,[
                    "s_cn"=>$_POST["request_cn"][$i],
                    "s_en"=>$_POST["request_en"][$i],
                    "s_regex"=>$_POST["request_regex"][$i],
                    "s_must"=>$_POST["request_must"][$i]
                ]);
            }
        }
        if(isset($_POST["response_en"])){
            for($i=0;$i<count($_POST["response_en"]);$i++){
                array_push($response,[
                    "s_cn"=>$_POST["response_cn"][$i],
                    "s_en"=>$_POST["response_en"][$i],
                    "s_regex"=>$_POST["response_regex"][$i],
                    "s_must"=>$_POST["response_must"][$i]
                ]);
            }
        }

        array_push($data,[
            "id"=>count($data)+1,
            "s_name"=>$_POST["s_name"],
            "s_method"=>$_POST["s_method"],
            "s_url"=>$_POST["s_url"],
            "request"=>$request,
            "response"=>$response
        ]);
        
        file_put_contents($_POST["s_project_path"]."/data/interface.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_edit(){
        if(!file_exists($_POST["s_project_path"]."/data/interface.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/interface.json"),true);
        // print_r($data);

        $request=[];
        $response=[];
        if(isset($_POST["request_en"])){
            for($i=0;$i<count($_POST["request_en"]);$i++){
                array_push($request,[
                    "s_cn"=>$_POST["request_cn"][$i],
                    "s_en"=>$_POST["request_en"][$i],
                    "s_regex"=>$_POST["request_regex"][$i],
                    "s_must"=>$_POST["request_must"][$i]
                ]);
            }
        }
        if(isset($_POST["response_en"])){
            for($i=0;$i<count($_POST["response_en"]);$i++){
                array_push($response,[
                    "s_cn"=>$_POST["response_cn"][$i],
                    "s_en"=>$_POST["response_en"][$i],
                    "s_regex"=>$_POST["response_regex"][$i],
                    "s_must"=>$_POST["response_must"][$i]
                ]);
            }
        }

        $data[$_POST["id"]-1]["s_method"]=$_POST["s_method"];
        $data[$_POST["id"]-1]["s_name"]=$_POST["s_name"];
        $data[$_POST["id"]-1]["s_url"]=$_POST["s_url"];
        $data[$_POST["id"]-1]["request"]=$request;
        $data[$_POST["id"]-1]["response"]=$response;
        file_put_contents($_POST["s_project_path"]."/data/interface.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_delete(){
        if(!file_exists($_POST["s_project_path"]."/data/interface.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/interface.json"),true);
        // print_r($data);
        $data[$_POST["id"]-1]["i_drop"]=1;
        file_put_contents($_POST["s_project_path"]."/data/interface.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_save(){
        if(!file_exists($_POST["s_project_path"]."/data/interface.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/interface.json"),true);
        if(!is_dir($_POST["s_project_path"]."/php")){
            mkdir($_POST["s_project_path"]."/php",0777);
        }
        if(!is_dir($_POST["s_project_path"]."/php/interfacer")){
            mkdir($_POST["s_project_path"]."/php/interfacer",0777);
        }
        foreach ($data as $key => $itrfc) {
            preg_match("/\?p=(.+)/",$itrfc["s_url"],$matchs);
            if(count($matchs)!=2){
                echo json_encode([
                    "res"=>"NG",
                    "message"=>"[".$itrfc["s_url"]."]URL匹配失败"
                ]);
            }
            $method=$itrfc["s_method"];
            $filename=strtolower($method)."_".$matchs[1].".php";
           
            $filter_must="if(!isset(";
            $filter_regex="";

            foreach ($itrfc["request"] as $key2 => $r) {
                $params='$_'.$method.'["'.str_replace("[]","",$r["s_en"]).'"]';

                $filter_regex.="if(isset({$params})){\n";

                //数组处理开始
                $white="";
                if(strpos($r["s_en"],"[]")!==false){
                    $filter_regex.="    foreach({$params} as \$key=>\$value){\n";
                    $params="\$value";
                    $white="    ";
                }
                
                $filter_regex.=$white."    if(!preg_match(\"".$r["s_regex"]."\",{$params})){\n";
                $filter_regex.=$white."        echo json_encode(['res'=>'NG','message'=>'[".$r["s_cn"]."]格式不合法']);\n";
                $filter_regex.=$white."        exit;\n";
                $filter_regex.=$white."    }\n";
                
                //数组处理结束
                if(strpos($r["s_en"],"[]")!==false){
                    $filter_regex.="    }\n";
                }
            
                if($r["s_must"]=="是"){
                    $filter_regex.="}else{\n";
                    $filter_regex.="    echo json_encode(['res'=>'NG','message'=>'[".$r["s_cn"]."]没有定义']);\n";
                    $filter_regex.="    exit;\n";
                    $filter_regex.="}\n";
                }else{
                    $filter_regex.="}\n";
                }
            }
            $php="<?php\n";
            $php.="//".date("Y-m-d H:i")."\n";
            $php.="//验证 ".$itrfc["s_name"]."\n";
            $php.=$filter_regex;
            $php.="?>";


            file_put_contents($_POST["s_project_path"]."/php/interfacer/".$filename,$php);
        }
        echo json_encode([
            "res"=>"OK","message"=>""
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_savecode(){
        if(!file_exists($_POST["s_project_path"]."/data/interface.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/interface.json"),true);
        if(!is_dir($_POST["s_project_path"]."/php")){
            mkdir($_POST["s_project_path"]."/php",0777);
        }
        if(!is_dir($_POST["s_project_path"]."/php/controler")){
            mkdir($_POST["s_project_path"]."/php/controler",0777);
        }
        if(!is_dir($_POST["s_project_path"]."/php/controler/bak")){
            mkdir($_POST["s_project_path"]."/php/controler/bak",0777);
        }
        $class=[];
        foreach ($data as $key => $itrfc) {
            preg_match("/\?p=(.+)/",$itrfc["s_url"],$matchs);
            if(count($matchs)!=2){
                echo json_encode([
                    "res"=>"NG",
                    "message"=>"[".$itrfc["s_url"]."]URL匹配失败"
                ]);
            }
            $method=$itrfc["s_method"];
            $sub=explode("_",$matchs[1]);
            if(!isset($class[$sub[0]])){
                $class[$sub[0]]=[];
            }
            array_push($class[$sub[0]],$method."_".$sub[1]);
        }

        foreach ($class as $key => $value) {
            $filename=$_POST["s_project_path"]."/php/controler/".$key.".php";
            if(is_file($filename)){
                continue;
            }
            // $bakfilename=$_POST["s_project_path"]."/php/controler/bak/".$key."_".date("YmdHis").".php";
            // if(is_file($filename)){
            //     copy($filename,$bakfilename);
            // }
            $php="<?php\n";
            $php.="use Sonkwl\xphp\apper;\n";
            $php.="class {$key}{\n";
            foreach ($value as $key2 => $func) {
                $php.="\n";
                $php.="    public static function {$func}(){}\n";
            }
            $php.="}\n";
            $php.="?>";
            file_put_contents($filename,$php);
        }

        self::CreateIndex();
        self::CreateConfig();

        echo json_encode([
            "res"=>"OK","message"=>""
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function CreateIndex(){
        if(!is_dir($_POST["s_project_path"]."/php")){
            mkdir($_POST["s_project_path"]."/php",0777);
        }
        $php="<?php\n";
        $php.="include \$_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';\n";
        $php.="use Sonkwl\xphp\apper;\n";
        $php.="apper::Start();\n";
        $php.='?>';
        file_put_contents($_POST["s_project_path"]."/php/index.php",$php);
    }

    public static function CreateConfig(){
        if(!is_dir($_POST["s_project_path"]."/php")){
            mkdir($_POST["s_project_path"]."/php",0777);
        }
        if(!is_dir($_POST["s_project_path"]."/php/config")){
            mkdir($_POST["s_project_path"]."/php/config",0777);
        }
        if(is_file($_POST["s_project_path"]."/php/config/config.php")){
            return;
        }
        $config="<?php\n";
        $config.="use Sonkwl\xphp\config;\n";
        $config.="config::Set([\n";
        $config.='    "dbname"=>"wh",'."\n";
        $config.='    "host"=>"10.202.8.204",'."\n";
        $config.='    "user"=>"123",'."\n";
        $config.='    "pwd"=>"123"'."\n";
        $config.="]);\n";
        $config.='?>';

        file_put_contents($_POST["s_project_path"]."/php/config/config.php",$config);
    }
}

interfacer::Run();
?>